package com.fary.jackson;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.introspect.AnnotationMap;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.io.IOException;
import java.text.DateFormat;
import java.text.FieldPosition;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Configuration
public class JacksonConfig implements Jackson2ObjectMapperBuilderCustomizer {

    @Bean
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
//        objectMapper.setSerializerFactory(objectMapper.getSerializerFactory().withSerializerModifier(new MyBeanSerializerModifier()));
        return objectMapper;
    }

    @Override
    public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
        jacksonObjectMapperBuilder.serializerByType(Date.class, new CustomizeDateSerializer());
        jacksonObjectMapperBuilder.deserializerByType(Date.class, new CustomizeDateDeserializer());
        jacksonObjectMapperBuilder.deserializerByType(String.class, new CustomizeStringDeserializer());
    }

    public static class CustomizeDateSerializer extends JsonSerializer<Date>  implements ContextualSerializer {

        private DateFormat df = null;

        @Override
        public void serialize(Date value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
            if (df != null) {
                gen.writeString(this.df.format(value));
            } else {
                gen.writeString(DateUtil.formatDate(value));
            }
        }

        @Override
        public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
            AnnotationMap annotated = property.getMember().getAllAnnotations();

            JsonFormat jsonFormat = annotated.get(JsonFormat.class);
            if (jsonFormat != null && jsonFormat.pattern() != null){
                df = new SimpleDateFormat(jsonFormat.pattern());
            }
            return this;
        }
    }

    public static class CustomizeDateDeserializer extends JsonDeserializer<Date> {
        @Override
        public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
            return DateUtil.parse(jsonParser.getValueAsString());
        }
    }

    public static class CustomizeStringDeserializer extends JsonDeserializer<String> {
        @Override
        public String deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
            return StrUtil.trim(jsonParser.getValueAsString());
        }
    }

    public class MyBeanSerializerModifier extends BeanSerializerModifier {

        @Override
        public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc, List<BeanPropertyWriter> beanProperties) {
            // 循环所有的beanPropertyWriter
            for (Object beanProperty : beanProperties) {
                BeanPropertyWriter writer = (BeanPropertyWriter) beanProperty;
                Class<?> clazz = writer.getType().getRawClass();
                //字符串
                if (String.class.equals(clazz)) {
                    writer.assignNullSerializer(new JsonSerializer<Object>() {
                        @Override
                        public void serialize(Object value, JsonGenerator jg, SerializerProvider sp) throws IOException, JsonProcessingException {
                            jg.writeString("");
                        }
                    });
                }
                //list
                else if (List.class.isAssignableFrom(clazz)) {
                    writer.assignNullSerializer(new JsonSerializer<Object>() {
                        @Override
                        public void serialize(Object value, JsonGenerator jg, SerializerProvider sp) throws IOException, JsonProcessingException {
                            jg.writeObject(Collections.EMPTY_LIST);
                        }
                    });
                }
                //map
                else if (Map.class.isAssignableFrom(clazz)) {
                    writer.assignNullSerializer(new JsonSerializer<Object>() {
                        @Override
                        public void serialize(Object value, JsonGenerator jg, SerializerProvider sp) throws IOException, JsonProcessingException {
                            jg.writeObject(Collections.EMPTY_MAP);
                        }
                    });
                }
                //String[]
                else if (String[].class.isAssignableFrom(clazz)) {
                    writer.assignNullSerializer(new JsonSerializer<Object>() {
                        @Override
                        public void serialize(Object value, JsonGenerator jg, SerializerProvider sp) throws IOException, JsonProcessingException {
                            jg.writeObject(new String[0]);
                        }
                    });
                }
                //其它
                else {
                    writer.assignNullSerializer(new JsonSerializer<Object>() {
                        @Override
                        public void serialize(Object value, JsonGenerator jg, SerializerProvider sp) throws IOException, JsonProcessingException {
                            jg.writeString("");
                        }
                    });
                }
            }
            return beanProperties;
        }
    }

}
